//
//  WBQRCodeViewController.swift
//  weibo
//
//  Created by Felix on 16/11/8.
//  Copyright © 2016年 Felix. All rights reserved.
//

import UIKit
import AVFoundation

class WBQRCodeViewController: UIViewController {
    @IBOutlet var contextView: UIView!

    @IBOutlet var textLabel: UILabel!
    
    @IBOutlet var costomTabbar: UITabBar!
    
    @IBOutlet var contextHeight: NSLayoutConstraint!
    @IBOutlet var scanLineTop: NSLayoutConstraint!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        ///设置为默认选中第一个按钮
        let item = costomTabbar.items?.first
        costomTabbar.selectedItem = item
        costomTabbar.delegate = self
        
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //开始扫描
        startScan()
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        startAnimation()

    }

    @IBAction func closeButtonClick(_ sender: AnyObject) {
        dismiss(animated: true) { }
    }


    @IBAction func photoButtonClick(_ sender: AnyObject) {
        
        //1.判断能否打开相册
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary){
            return
        }
        
        ///2.打开相册
        let pick =  UIImagePickerController()
        pick.delegate = self
        present(pick, animated: true) { }
    }
    
    ///开始动画
     func startAnimation(){
        scanLineTop.constant = -contextHeight.constant
        view.layoutIfNeeded()
        UIView.animate(withDuration: 2.0) {
            UIView.setAnimationRepeatCount(MAXFLOAT)
            self.scanLineTop.constant = self.contextHeight.constant
            self.view.layoutIfNeeded()
        }
    }
    
    private func startScan(){
        //1.判断是否能加入输入设备
        if !session.canAddInput(input){
            return
        }
        
        //2.判断能否加入输出设备
        if !session.canAddOutput(output){
            return
        }
        
        //3.加入输入设备
        session.addInput(input)
        
        
        //4.加入输出设备
        session.addOutput(output)
        
        //5.设置输出能够解析的数据类型
        output?.metadataObjectTypes = output?.availableMetadataObjectTypes
        
        //6.设置代理

        output?.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        
        //7，添加预览图层
        view.layer.insertSublayer(previewLayer, at: 0)
        previewLayer.frame = UIScreen.main.bounds
        
        view.layer.addSublayer(contentLayer)
        contentLayer.frame = UIScreen.main.bounds
        
        
        //8.开始扫描
        session.startRunning()
    }
    
    //1.输入设备
    private lazy var input:AVCaptureDeviceInput? = {
        let dc = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        return try? AVCaptureDeviceInput.init(device: dc)
    }()
    
    //2.会话
    private lazy var session:AVCaptureSession = AVCaptureSession()
    
    //3.输出设备
    
    private lazy var output:AVCaptureMetadataOutput? = {
        let out =  AVCaptureMetadataOutput()
        let viewFrame = self.view.frame
        
        //1.由于拿到的容器视图宽高一直不对、所以创建一个临时视图
        let stempView = UIView.init(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        stempView.center = self.view.center
        
        //2.取值区域是横屏的坐标系、所以要把view的竖屏坐标系转换为横屏坐标系（默认为0，0，1，1）
        let contentFrame = stempView.frame
        let x = contentFrame.origin.y / viewFrame.size.height
        let y = contentFrame.origin.x / viewFrame.size.width
        
        let width = contentFrame.size.height / viewFrame.size.height
        
        let height = contentFrame.size.width / viewFrame.size.width
        
        out.rectOfInterest = CGRect(x: x, y: y, width: width, height: height)
        
        
        return out
    }()
    
    //4.预览图层
      lazy var previewLayer: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)
    
    //5.二维码定位图层
    lazy var contentLayer:CALayer  = CALayer()
}

// 点击tabbar按钮设置扫描框高度
extension WBQRCodeViewController:UITabBarDelegate{
    func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem){
        contextHeight.constant = (item.tag == 1) ? 300 : 150
        view.layoutIfNeeded()
        view.layer.removeAllAnimations()
        startAnimation()
    }
}


//二维码扫描结果回调
extension WBQRCodeViewController:AVCaptureMetadataOutputObjectsDelegate{
    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!){
        
        ///1.清除定位图层
        clearLayer()
        
        ///2.判断是否有数据
        guard let mete = (metadataObjects.last as? AVMetadataObject) else {
            return
        }
        
        ///3.将读取到的数据转换为机器可以读取的格式
        let objc  = self.previewLayer.transformedMetadataObject(for: mete) as? AVMetadataMachineReadableCodeObject
        
        ///4.判断是否有值
        guard let str = objc?.stringValue else {
            return
        }
        ///5.给结果显示label显示结果
        textLabel.text = str
        
        ///6.绘制定位框
        drawLine(mete: objc!)
    
    }
    
    
    //绘制二维码定位框
    func drawLine(mete:AVMetadataMachineReadableCodeObject) -> Void {
        
        //1.校验安全
        guard let conners = mete.corners else {
            return
        }
        
        
        
        //2.创建图层
        let layer = CAShapeLayer()
        layer.lineWidth = 5
        layer.strokeColor = UIColor.green.cgColor
        layer.fillColor = UIColor.clear.cgColor
        
        //3.创建路径
        let path = UIBezierPath()
        var index = 0
        
        //4.添加第一个点
        let point = CGPoint.init(dictionaryRepresentation: conners[index] as! CFDictionary)
        
        path.move(to: point!)
        index += 1
        
        //5.添加其他线
        while index < conners.count {
            let point = CGPoint.init(dictionaryRepresentation: conners[index] as! CFDictionary)
            index += 1
            path.addLine(to: point!)
        }
        path.close()

        layer.path = path.cgPath
        
        contentLayer.addSublayer(layer)
    }
    
    
    //清空二维码定位图层
    func clearLayer() {
        guard let array = contentLayer.sublayers else {
            return
        }
        for item in array {
            item.removeFromSuperlayer()
        }
    }
}



//MARK: -识别图片二维码
extension WBQRCodeViewController:UIImagePickerControllerDelegate , UINavigationControllerDelegate{
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        //1.获取图片
        guard let image = info["UIImagePickerControllerOriginalImage"] as? UIImage else {
            return
        }
        ///2.0创建图片
        guard let ciImage = CIImage.init(image: image) else {
            return
        }
        
        //2.1创建探测器（设置为高精度）
        let detector =  CIDetector(ofType: CIDetectorTypeQRCode, context: nil, options: [CIDetectorAccuracy:CIDetectorAccuracyHigh])
        
        //2.2用探测器从图片中获取数据
        let results = detector?.features(in: ciImage)
        // 2.3取出探测到的数据
        for result in results!
        {
            AdaLog(message: (result as! CIQRCodeFeature).messageString)
        }

        picker.dismiss(animated: true, completion: nil)
    
        
        
    }
}
